import Vue from 'vue'
import Router from 'vue-router'
import Index from '../views/index.vue'
import Cookies from 'js-cookie'
Vue.use(Router) // 使用vue-router插件

const TokenKey = 'Admin-Token'
function setToken(token) {
  return Cookies.set(TokenKey, token)
}
function GetQueryString(name) {
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  var r = window.location.href.split('?')[1] ? window.location.href.split('?')[1].match(reg) : null
  if (r != null) return unescape(r[2]);
  return null
}
const constantRoutes = [
  {
    path: '/',
    name: 'Index',
    component: Index
  },
  {
    path: '/Preview',
    name: 'Preview',
    // 路由懒加载
    component: () => import('../views/Preview.vue')
  },
  {
    path: '/Type',
    name: 'Type',
    component: () => import('../views/Type.vue')
  }
]

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  });
const router = createRouter();

router.beforeEach(async(to, from, next) => {
  // 获取地址栏token
  const accessToken = GetQueryString('accessToken') || Cookies.get('Admin-Token')
  if (accessToken) {
      setToken(accessToken)
  }
  next()
})
export default router